#!/usr/bin/env python3
"""
Unified Configuration Manager - Intelligent Rules V2 Foundation Core
严格遵循 rules/system/unified_configuration_management.yaml
"""

import os
import yaml
from typing import Dict, Any, Optional
from pathlib import Path
import logging

logger = logging.getLogger(__name__)

class UnifiedConfigManager:
    """统一配置管理器 - 基于rules的完美实现"""
    
    def __init__(self, project_root: str = None, environment: str = None):
        self.project_root = Path(project_root) if project_root else Path.cwd()
        self.environment = environment or os.getenv("APP_ENV", "development")
        self.config_root = self.project_root / "config"
        self._config_cache = {}
        self._ensure_directory_structure()
        
    def _ensure_directory_structure(self):
        """确保配置目录结构存在"""
        dirs = [
            self.config_root / "values",
            self.config_root / "environments" / "development",
            self.config_root / "environments" / "production"
        ]
        for d in dirs:
            d.mkdir(parents=True, exist_ok=True)
    
    def load_configuration(self, config_name: str) -> Dict[str, Any]:
        """加载配置 - 层级继承策略"""
        cache_key = f"{config_name}_{self.environment}"
        if cache_key in self._config_cache:
            return self._config_cache[cache_key]
        
        # 加载基础配置
        base_config = self._load_base_config(config_name)
        # 加载环境配置
        env_config = self._load_env_config(config_name)
        # 合并配置
        merged = self._deep_merge(base_config, env_config)
        
        self._config_cache[cache_key] = merged
        return merged
    
    def _load_base_config(self, config_name: str) -> Dict[str, Any]:
        """加载基础配置"""
        config_file = self.config_root / "values" / f"{config_name}.yaml"
        if not config_file.exists():
            return {}
        try:
            with open(config_file, "r", encoding="utf-8") as f:
                return yaml.safe_load(f) or {}
        except Exception:
            return {}
    
    def _load_env_config(self, config_name: str) -> Dict[str, Any]:
        """加载环境配置"""
        env_file = self.config_root / "environments" / self.environment / f"{config_name}.yaml"
        if not env_file.exists():
            return {}
        try:
            with open(env_file, "r", encoding="utf-8") as f:
                return yaml.safe_load(f) or {}
        except Exception:
            return {}
    
    def _deep_merge(self, base: Dict[str, Any], overlay: Dict[str, Any]) -> Dict[str, Any]:
        """深度合并配置"""
        result = base.copy()
        for key, value in overlay.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._deep_merge(result[key], value)
            else:
                result[key] = value
        return result
    
    def get_connection_for_context(self, context: str = "default") -> Dict[str, Any]:
        """企业级端口标准化"""
        db_config = self.load_configuration("database")
        port_mapping = {
            "api_service": 8123,
            "admin_tools": 9000,
            "default": 8123
        }
        port = port_mapping.get(context, 8123)
        config = db_config.copy()
        config["port"] = port
        return config

# 便捷函数
_global_manager = None

def get_config_manager() -> UnifiedConfigManager:
    global _global_manager
    if _global_manager is None:
        _global_manager = UnifiedConfigManager()
    return _global_manager

def load_config(config_name: str) -> Dict[str, Any]:
    return get_config_manager().load_configuration(config_name)

if __name__ == "__main__":
    print("🧪 Testing Unified Config Manager V2...")
    manager = UnifiedConfigManager()
    print("✅ Unified Config Manager V2 initialized successfully!")

